package com.wiloon.java8x.xml;

/**
 * Created with IntelliJ IDEA.
 * User: w1100n
 * Date: 11/20/13
 * Time: 2:45 PM
 */

import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class SAXParser {
    public static final Logger logger = Logger.getLogger(SAXParser.class);

    class BookHandler extends DefaultHandler {
        private List<String> nameList;
        private boolean title = false;

        public List<String> getNameList() {
            return nameList;
        }

        // Called at start of an XML document
        @Override
        public void startDocument() throws SAXException {
            logger.debug("Start parsing document...");
            nameList = new ArrayList();
        }

        // Called at end of an XML document
        @Override
        public void endDocument() throws SAXException {
            logger.debug("End");
        }

        /**
         * Start processing of an element.
         *
         * @param localName  The local name, without prefix
         * @param qName      The qualified name, with prefix
         * @param attributes The attributes of the element
         */
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            logger.debug("start element, uri=" + uri + ",localName=" + localName + ",qName=" + qName + ",atts=" + attributes);
            // Using qualified name because we are not using xmlns prefixes here.
            if (qName.equals("book"))
                for (int i = 0; i < attributes.getLength(); i++) {
                    String attrName = attributes.getQName(i);
                    String attrValue = attributes.getValue(i);
                    logger.debug("attributes:" + attrName + "=" + attrValue);
                }

            if (qName.equals("title")) {
                title = true;
            }
        }

        @Override
        public void endElement(String namespaceURI, String localName, String qName)
                throws SAXException {
            logger.debug("end element.");
            // End of processing current element
            if (title) {
                title = false;
            }
        }

        @Override
        public void characters(char[] ch, int start, int length) {
            logger.debug("characters, ch=" + ch + ",start=" + start + ",length=" + length);
            // Processing character data inside an element
            if (title) {
                String bookTitle = new String(ch, start, length);
                System.out.println("Book title: " + bookTitle);
                nameList.add(bookTitle);
            }
        }
    }

    public static void main(String[] args) throws SAXException, IOException {
        XMLReader parser = XMLReaderFactory.createXMLReader();
        BookHandler bookHandler = (new SAXParser()).new BookHandler();
        parser.setContentHandler(bookHandler);
        ClassLoader classLoader = SAXParser.class.getClassLoader();
        URL url = classLoader.getResource("com/wiloon/test/java/xml/test.xml");
        logger.debug("url:" + url);
        parser.parse(url.toString());
        System.out.println(bookHandler.getNameList());
    }
}
